<template>
  <div class="main-app-data-demo">
    <div class="page-header">
      <h1>子应用2 - 主应用数据交互案例</h1>
      <el-tag type="primary" size="large">{{ appInfo.appType.toUpperCase() }}</el-tag>
    </div>

    <!-- 环境信息 -->
    <el-card class="demo-card" header="环境信息">
      <div class="info-grid">
        <div class="info-item">
          <strong>应用名称:</strong>
          <span>{{ appInfo.subAppName || '子应用2' }}</span>
        </div>
        <div class="info-item">
          <strong>运行模式:</strong>
          <el-tag :type="appInfo.isSubApp ? 'success' : 'warning'">
            {{ appInfo.isSubApp ? '微前端模式' : '独立模式' }}
          </el-tag>
        </div>
        <div class="info-item">
          <strong>路由模式:</strong>
          <span>{{ appInfo.routerMode }}</span>
        </div>
        <div class="info-item">
          <strong>主应用连接:</strong>
          <el-tag :type="hasMainAppConnection ? 'success' : 'danger'">
            {{ hasMainAppConnection ? '已连接' : '未连接' }}
          </el-tag>
        </div>
      </div>
    </el-card>

    <!-- 实时数据监控 -->
    <el-card class="demo-card" header="实时数据监控">
      <div class="monitor-section">
        <div class="data-display">
          <h4>全局状态实时监控:</h4>
          <div class="monitor-grid">
            <div class="monitor-item">
              <strong>用户信息:</strong>
              <pre v-if="globalState?.user">{{ JSON.stringify(globalState.user, null, 2) }}</pre>
              <span v-else class="no-data">暂无数据</span>
            </div>
            <div class="monitor-item">
              <strong>当前主题:</strong>
              <el-tag :type="getThemeTagType(globalState?.theme)">
                {{ globalState?.theme || '未设置' }}
              </el-tag>
            </div>
            <div class="monitor-item">
              <strong>语言设置:</strong>
              <span>{{ globalState?.language || '未设置' }}</span>
            </div>
            <div class="monitor-item">
              <strong>通知数量:</strong>
              <el-badge :value="notificationCount" :max="99">
                <el-button size="small">通知</el-button>
              </el-badge>
            </div>
          </div>
        </div>

        <div class="auto-refresh">
          <el-switch
            v-model="autoRefresh"
            active-text="自动刷新"
            inactive-text="手动刷新"
            @change="toggleAutoRefresh"
          />
          <el-button @click="refreshData" :disabled="autoRefresh">立即刷新</el-button>
        </div>
      </div>
    </el-card>

    <!-- 高级交互功能 -->
    <el-card class="demo-card" header="高级交互功能">
      <div class="advanced-section">
        <div class="feature-group">
          <h4>数据同步测试:</h4>
          <div class="action-buttons">
            <el-button type="primary" @click="syncUserData">同步用户数据</el-button>
            <el-button type="success" @click="syncThemeSettings">同步主题设置</el-button>
            <el-button type="info" @click="syncLanguageSettings">同步语言设置</el-button>
          </div>
        </div>

        <div class="feature-group">
          <h4>批量操作:</h4>
          <div class="batch-operations">
            <el-button type="warning" @click="batchSendNotifications">批量发送通知</el-button>
            <el-button type="danger" @click="clearAllNotifications">清空所有通知</el-button>
            <el-button @click="exportGlobalState">导出全局状态</el-button>
          </div>
        </div>

        <div class="feature-group">
          <h4>性能测试:</h4>
          <div class="performance-test">
            <el-input-number 
              v-model="testCount" 
              :min="1" 
              :max="1000" 
              label="测试次数"
            />
            <el-button type="primary" @click="performanceTest" :loading="isPerformanceTesting">
              {{ isPerformanceTesting ? '测试中...' : '开始性能测试' }}
            </el-button>
            <div v-if="performanceResult" class="performance-result">
              <p>测试结果: 平均耗时 {{ performanceResult.avgTime }}ms</p>
              <p>总耗时: {{ performanceResult.totalTime }}ms</p>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 自定义事件系统 -->
    <el-card class="demo-card" header="自定义事件系统">
      <div class="event-section">
        <div class="event-sender">
          <h4>发送自定义事件:</h4>
          <el-form :model="eventForm" label-width="100px">
            <el-form-item label="事件名称:">
              <el-input v-model="eventForm.name" placeholder="请输入事件名称" />
            </el-form-item>
            <el-form-item label="事件数据:">
              <el-input 
                v-model="eventForm.data" 
                type="textarea" 
                :rows="3"
                placeholder="请输入JSON格式的事件数据" 
              />
            </el-form-item>
            <el-form-item label="目标:">
              <el-select v-model="eventForm.target" placeholder="选择事件目标">
                <el-option label="主应用" value="main" />
                <el-option label="所有子应用" value="all-sub" />
                <el-option label="子应用1" value="sub-app1" />
                <el-option label="广播" value="broadcast" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="sendCustomEvent">发送事件</el-button>
            </el-form-item>
          </el-form>
        </div>

        <div class="event-log">
          <h4>事件日志 (最近20条):</h4>
          <div class="log-container">
            <div 
              v-for="(log, index) in eventLogs.slice(-20)" 
              :key="index"
              class="log-item"
              :class="log.type"
            >
              <div class="log-time">{{ log.timestamp }}</div>
              <div class="log-content">
                <strong>{{ log.type === 'sent' ? '发送' : '接收' }}:</strong> 
                {{ log.eventName }}
              </div>
              <div class="log-data" v-if="log.data">
                <pre>{{ JSON.stringify(log.data, null, 2) }}</pre>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- WebSocket 模拟 -->
    <el-card class="demo-card" header="WebSocket 模拟 (子应用间通信)">
      <div class="websocket-section">
        <div class="connection-status">
          <h4>连接状态:</h4>
          <el-tag :type="wsConnected ? 'success' : 'danger'">
            {{ wsConnected ? '已连接' : '未连接' }}
          </el-tag>
          <el-button 
            @click="toggleWebSocket" 
            :type="wsConnected ? 'danger' : 'success'"
            size="small"
          >
            {{ wsConnected ? '断开连接' : '建立连接' }}
          </el-button>
        </div>

        <div class="message-panel" v-if="wsConnected">
          <div class="send-message">
            <h4>发送消息:</h4>
            <el-input 
              v-model="wsMessage" 
              placeholder="输入要发送的消息"
              @keyup.enter="sendWebSocketMessage"
            />
            <el-button type="primary" @click="sendWebSocketMessage">发送</el-button>
          </div>

          <div class="message-history">
            <h4>消息历史:</h4>
            <div class="message-list">
              <div 
                v-for="(msg, index) in wsMessages" 
                :key="index"
                class="message-item"
              >
                <span class="message-time">{{ msg.timestamp }}</span>
                <span class="message-content">{{ msg.content }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 调试面板 -->
    <el-card class="demo-card" header="调试面板" v-if="isDev">
      <div class="debug-panel">
        <el-tabs v-model="activeDebugTab">
          <el-tab-pane label="Props数据" name="props">
            <pre>{{ JSON.stringify(mainAppProps, null, 2) }}</pre>
          </el-tab-pane>
          <el-tab-pane label="全局状态" name="state">
            <pre>{{ JSON.stringify(globalState, null, 2) }}</pre>
          </el-tab-pane>
          <el-tab-pane label="应用信息" name="app">
            <pre>{{ JSON.stringify(appInfo.debugInfo, null, 2) }}</pre>
          </el-tab-pane>
          <el-tab-pane label="性能数据" name="performance">
            <pre>{{ JSON.stringify(performanceData, null, 2) }}</pre>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { ElMessage, ElNotification } from 'element-plus'
import { useQiankun } from '@/utils/qiankun'

// 使用 qiankun 工具函数
const appInfo = useQiankun()

// 响应式数据
const globalState = ref(null)
const autoRefresh = ref(false)
const testCount = ref(10)
const isPerformanceTesting = ref(false)
const performanceResult = ref(null)
const performanceData = ref({})
const isDev = import.meta.env.DEV
const activeDebugTab = ref('props')

// 事件系统
const eventForm = ref({
  name: 'customEvent',
  data: '{"message": "Hello from sub-app2"}',
  target: 'main'
})
const eventLogs = ref([])

// WebSocket 模拟
const wsConnected = ref(false)
const wsMessage = ref('')
const wsMessages = ref([])

// 定时器
let refreshTimer = null

// 计算属性
const mainAppProps = computed(() => appInfo.props)
const hasMainAppConnection = computed(() => !!mainAppProps.value)
const notificationCount = computed(() => {
  return globalState.value?.sharedData?.notifications?.length || 0
})

// 方法
const refreshData = () => {
  if (appInfo.subAppData) {
    globalState.value = appInfo.subAppData.getGlobalState()
  }
}

const toggleAutoRefresh = (value) => {
  if (value) {
    refreshTimer = setInterval(refreshData, 2000) // 每2秒刷新一次
  } else {
    if (refreshTimer) {
      clearInterval(refreshTimer)
      refreshTimer = null
    }
  }
}

const getThemeTagType = (theme) => {
  const themeTypes = {
    'light': 'info',
    'dark': 'warning',
    'blue': 'primary',
    'green': 'success'
  }
  return themeTypes[theme] || 'info'
}

// 高级交互功能
const syncUserData = () => {
  if (appInfo.subAppData) {
    const userData = {
      id: Date.now(),
      name: '子应用2同步用户',
      role: 'sync-user',
      department: '数据同步部',
      from: '子应用2',
      syncTime: new Date().toISOString()
    }
    appInfo.subAppData.updateUser(userData)
    ElMessage.success('用户数据已同步')
    addEventLog('sent', 'syncUserData', userData)
  }
}

const syncThemeSettings = () => {
  if (appInfo.subAppData) {
    const themes = ['light', 'dark', 'blue', 'green']
    const randomTheme = themes[Math.floor(Math.random() * themes.length)]
    appInfo.subAppData.switchTheme(randomTheme)
    ElMessage.success(`主题已同步为: ${randomTheme}`)
    addEventLog('sent', 'syncTheme', { theme: randomTheme })
  }
}

const syncLanguageSettings = () => {
  if (appInfo.subAppData) {
    const languages = ['zh-CN', 'en-US', 'ja-JP', 'ko-KR']
    const randomLang = languages[Math.floor(Math.random() * languages.length)]
    // 这里模拟语言设置同步
    appInfo.subAppData.updateSharedData({ language: randomLang })
    ElMessage.success(`语言已同步为: ${randomLang}`)
    addEventLog('sent', 'syncLanguage', { language: randomLang })
  }
}

const batchSendNotifications = async () => {
  if (!appInfo.subAppData) return
  
  const notifications = [
    { title: '批量通知1', message: '这是第一条批量通知', type: 'info' },
    { title: '批量通知2', message: '这是第二条批量通知', type: 'success' },
    { title: '批量通知3', message: '这是第三条批量通知', type: 'warning' }
  ]

  for (let i = 0; i < notifications.length; i++) {
    await new Promise(resolve => setTimeout(resolve, 500)) // 延迟500ms
    appInfo.subAppData.sendNotification({
      ...notifications[i],
      from: '子应用2',
      batchId: Date.now()
    })
  }
  
  ElMessage.success('批量通知发送完成')
  addEventLog('sent', 'batchNotifications', { count: notifications.length })
}

const clearAllNotifications = () => {
  if (appInfo.subAppData) {
    appInfo.subAppData.updateSharedData({ notifications: [] })
    ElMessage.success('所有通知已清空')
    addEventLog('sent', 'clearNotifications')
  }
}

const exportGlobalState = () => {
  const state = globalState.value
  if (state) {
    const dataStr = JSON.stringify(state, null, 2)
    const blob = new Blob([dataStr], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `global-state-${Date.now()}.json`
    a.click()
    URL.revokeObjectURL(url)
    ElMessage.success('全局状态已导出')
    addEventLog('sent', 'exportState')
  }
}

const performanceTest = async () => {
  if (!appInfo.subAppData) return
  
  isPerformanceTesting.value = true
  const startTime = performance.now()
  const times = []
  
  try {
    for (let i = 0; i < testCount.value; i++) {
      const iterationStart = performance.now()
      
      // 执行一系列操作
      appInfo.subAppData.updateSharedData({ 
        testIteration: i, 
        timestamp: Date.now() 
      })
      
      const iterationEnd = performance.now()
      times.push(iterationEnd - iterationStart)
      
      // 每10次操作暂停一下，避免阻塞UI
      if (i % 10 === 0) {
        await new Promise(resolve => setTimeout(resolve, 1))
      }
    }
    
    const totalTime = performance.now() - startTime
    const avgTime = times.reduce((a, b) => a + b, 0) / times.length
    
    performanceResult.value = {
      totalTime: totalTime.toFixed(2),
      avgTime: avgTime.toFixed(2),
      iterations: testCount.value
    }
    
    performanceData.value = {
      ...performanceResult.value,
      times: times,
      timestamp: new Date().toISOString()
    }
    
    ElMessage.success('性能测试完成')
    addEventLog('sent', 'performanceTest', performanceResult.value)
  } catch (error) {
    ElMessage.error('性能测试失败: ' + error.message)
  } finally {
    isPerformanceTesting.value = false
  }
}

// 事件系统
const addEventLog = (type, eventName, data = null) => {
  eventLogs.value.push({
    type,
    eventName,
    data,
    timestamp: new Date().toLocaleString()
  })
}

const sendCustomEvent = () => {
  try {
    const eventData = eventForm.value.data ? JSON.parse(eventForm.value.data) : {}
    
    // 模拟发送自定义事件
    if (appInfo.subAppData) {
      appInfo.subAppData.updateSharedData({
        customEvent: {
          name: eventForm.value.name,
          data: eventData,
          target: eventForm.value.target,
          from: '子应用2',
          timestamp: new Date().toISOString()
        }
      })
    }
    
    // 也可以通过 window 事件系统发送
    window.dispatchEvent(new CustomEvent(eventForm.value.name, {
      detail: {
        ...eventData,
        from: '子应用2',
        target: eventForm.value.target
      }
    }))
    
    ElMessage.success('自定义事件已发送')
    addEventLog('sent', eventForm.value.name, eventData)
  } catch (error) {
    ElMessage.error('事件数据格式错误: ' + error.message)
  }
}

// WebSocket 模拟
const toggleWebSocket = () => {
  wsConnected.value = !wsConnected.value
  if (wsConnected.value) {
    ElNotification.success({
      title: 'WebSocket',
      message: '连接已建立'
    })
    addEventLog('received', 'websocketConnected')
  } else {
    ElNotification.info({
      title: 'WebSocket',
      message: '连接已断开'
    })
    addEventLog('sent', 'websocketDisconnected')
  }
}

const sendWebSocketMessage = () => {
  if (!wsConnected.value || !wsMessage.value.trim()) return
  
  const message = {
    content: wsMessage.value,
    timestamp: new Date().toLocaleString(),
    from: '子应用2'
  }
  
  wsMessages.value.push(message)
  
  // 模拟通过主应用转发消息
  if (appInfo.subAppData) {
    appInfo.subAppData.updateSharedData({
      wsMessage: message
    })
  }
  
  wsMessage.value = ''
  addEventLog('sent', 'websocketMessage', message)
}

// 监听全局状态变化
watch(() => globalState.value, (newState, oldState) => {
  if (newState && oldState) {
    // 检查具体变化
    if (newState.user !== oldState.user) {
      addEventLog('received', 'userChanged', newState.user)
    }
    if (newState.theme !== oldState.theme) {
      addEventLog('received', 'themeChanged', { theme: newState.theme })
    }
    if (newState.sharedData?.notifications?.length !== oldState.sharedData?.notifications?.length) {
      addEventLog('received', 'notificationChanged', { 
        count: newState.sharedData?.notifications?.length 
      })
    }
  }
}, { deep: true })

// 生命周期
onMounted(() => {
  console.log('[子应用2] 组件挂载，qiankun 信息:', appInfo)
  refreshData()
  
  // 设置事件监听
  const handleCustomEvent = (event) => {
    addEventLog('received', event.type, event.detail)
  }
  
  // 监听各种自定义事件
  const eventTypes = ['userChanged', 'themeChanged', 'notificationReceived', 'customEvent']
  eventTypes.forEach(type => {
    window.addEventListener(type, handleCustomEvent)
  })
  
  // 清理函数
  const cleanup = () => {
    eventTypes.forEach(type => {
      window.removeEventListener(type, handleCustomEvent)
    })
    if (refreshTimer) {
      clearInterval(refreshTimer)
    }
  }
  
  // 保存清理函数
  onUnmounted(cleanup)
  
  addEventLog('sent', 'componentMounted')
})
</script>

<style scoped>
.main-app-data-demo {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 2px solid #e4e7ed;
}

.demo-card {
  margin-bottom: 20px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 15px;
}

.info-item {
  padding: 12px;
  background: #f5f7fa;
  border-radius: 6px;
  border-left: 4px solid #409eff;
}

.info-item strong {
  color: #303133;
  margin-right: 8px;
}

.monitor-section {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.monitor-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 15px;
  margin-top: 15px;
}

.monitor-item {
  padding: 15px;
  background: #f0f9ff;
  border: 1px solid #bfdbfe;
  border-radius: 8px;
}

.monitor-item pre {
  margin: 8px 0 0 0;
  font-size: 12px;
  background: #ffffff;
  padding: 8px;
  border-radius: 4px;
}

.no-data {
  color: #909399;
  font-style: italic;
}

.auto-refresh {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px;
  background: #fafbfc;
  border-radius: 8px;
}

.advanced-section {
  display: flex;
  flex-direction: column;
  gap: 25px;
}

.feature-group {
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #67c23a;
}

.feature-group h4 {
  margin-bottom: 15px;
  color: #303133;
}

.action-buttons, .batch-operations {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.performance-test {
  display: flex;
  align-items: center;
  gap: 15px;
  flex-wrap: wrap;
}

.performance-result {
  padding: 10px;
  background: #e7f7ff;
  border-radius: 4px;
  font-size: 14px;
}

.event-section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 30px;
}

.event-sender, .event-log {
  padding: 20px;
  background: #fafbfc;
  border-radius: 8px;
}

.event-sender h4, .event-log h4 {
  margin-bottom: 15px;
  color: #303133;
}

.log-container {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.log-item {
  padding: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.log-item:last-child {
  border-bottom: none;
}

.log-item.sent {
  background: #f0f9ff;
}

.log-item.received {
  background: #f0fdf4;
}

.log-time {
  font-size: 12px;
  color: #909399;
  margin-bottom: 5px;
}

.log-content {
  margin-bottom: 8px;
}

.log-data pre {
  background: #fafafa;
  padding: 8px;
  border-radius: 4px;
  font-size: 11px;
  margin: 0;
}

.websocket-section {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.connection-status {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 8px;
}

.message-panel {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.send-message, .message-history {
  padding: 15px;
  background: #fafbfc;
  border-radius: 8px;
}

.send-message h4, .message-history h4 {
  margin-bottom: 15px;
}

.send-message {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.message-list {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.message-item {
  padding: 8px 12px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
}

.message-item:last-child {
  border-bottom: none;
}

.message-time {
  font-size: 12px;
  color: #909399;
}

.message-content {
  font-weight: 500;
}

.debug-panel {
  max-height: 500px;
  overflow-y: auto;
}

.debug-panel pre {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  font-size: 12px;
  line-height: 1.4;
}

@media (max-width: 768px) {
  .event-section, .message-panel {
    grid-template-columns: 1fr;
  }
  
  .monitor-grid {
    grid-template-columns: 1fr;
  }
}
</style> 